<template>
  <div>
    <el-button
      type="warning"
      icon="el-icon-setting"
      circle
      @click="assignRole"
    ></el-button>

    <!-- #region Dialog -->
    <el-dialog
      title="分配角色"
      :visible.sync="isVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="assignRoleFromRef"
        :model="roleForm"
        :rules="assignFormRole"
        label-width="80px"
        status-icon
      >
        <el-form-item label="用户名">
          <xy-input v-model="roleForm.userName" disabled></xy-input>
        </el-form-item>
        <el-form-item label="当前角色" prop="roleId">
          <el-select v-model="roleForm.roleId" clearable placeholder="请选择">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit('assignRoleFromRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- #endregion -->
  </div>
</template>

<script>
export default {
  props: {
    user: Object,
  },

  data() {
    return {
      roles: [],
      isVisible: false,
      roleForm: { roleId: 0 },
      assignFormRole: {
        roleId: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
    };
  },
  created() {},
  methods: {
    async getUserRole() {
      let response = await this.$http.Get("/api/Roles");
      if (response.ok) {
        this.roles = response.data;
      } else {
        console.error(response);
      }
    },
    assignRole() {
      this.isVisible = true;
      // this.roleForm = this.user;
      this.getUserRole();
      console.log(this.user);
      this.roleForm.roleId = this.user.role.id;
      this.roleForm.userName = this.user.userName;
      this.roleForm.userId = this.user.id;
    },
    handleClose() {
      this.isVisible = false;
    },
    onSubmit(formName) {
      console.log(this.$refs[formName]);
      this.$refs[formName].validate(async (valided) => {
        if (!valided) {
          return;
        }
        try {
          // let response = await this.$myhttp.put(
          //   "User",
          //   this.roleForm.userName,
          //   this.roleForm
          // );
          // console.log(response);
          this.isVisible = false;
          this.$message.success("修改成功");
          console.log(this.roleForm);
          //  this.$emit("selectedRoles", this.roleForm);
        } catch (error) {
          console.error(error);
          this.$message.error("修改失败");
        }
      });
    },
  },
};
</script>

<style></style>
